﻿// <copyright file="ContentHeader.cs" company="Sinclair Community College">
// Copyright 2010 Sinclair Community College
// </copyright>
// <originalAuthor>Patrick S. Seymour (patrick.seymour@gmail.com)</originalAuthor>

namespace SinclairCC.AppV
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;

    /// <summary>
    /// This class represents the Content Header section in an App-V SFT/DSFT file.
    /// </summary>
    /// <remarks>
    /// <para>
    /// The Content header serves the purpose of storing the historical metadata
    /// about the environment under which the package was created and subsequently updated.
    /// Another critical function for Content header section is to store linearity for the
    /// package, namely a list of past and current version GUID(s) which are used by App-V
    /// to track the lineage of a package.
    /// </para>
    /// <para>
    /// The CONT header metadata section does not exist in versions older than 4.0.
    /// </para>
    /// </remarks>
    public class ContentHeader : HeaderMetadataSection
    {
        /// <summary>
        /// This field is reserved and is initialized to all zeroes.
        /// </summary>
        [SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields", Justification = "This field is marked as reserved in the App-V File Format Specification.")]
        private byte[] reserved;

        /// <summary>
        /// The number of version GUIDs following immediately after the CONT header.
        /// </summary>
        /// <remarks>
        /// For version 4.5 and above packages, this count is reset back to one (the
        /// list containing only the current version GUID) if a package is branched
        /// to a new package.
        /// </remarks>
        private int versionGuidCount;

        /// <summary>
        /// The number of history entries following the version GUID list.
        /// </summary>
        private int historyEntryCount;

        /// <summary>
        /// The version GUIDs for the package.
        /// </summary>
        /// <remarks>
        /// The version GUIDs appear immediately after the CONT header.
        /// </remarks>
        private List<Guid> versionGuids;

        /// <summary>
        /// The history entries for the package.
        /// </summary>
        /// <remarks>
        /// The history entries appear immediately after the version GUIDs.
        /// </remarks>
        private List<HistoryEntry> historyEntries;

        /// <summary>
        /// Initializes a new instance of the ContentHeader class.
        /// </summary>
        /// <param name="fileReader">
        /// A binary file reader that points to the SFT file.
        /// </param>
        public ContentHeader(System.IO.BinaryReader fileReader)
            : base(fileReader)
        {
        }

        /// <summary>
        /// Gets the version GUIDs for the package.
        /// </summary>
        public List<Guid> VersionGuids
        {
            get
            {
                this.ReadSection();
                return this.versionGuids;
            }
        }

        /// <summary>
        /// Gets the history entries for the package.
        /// </summary>
        public List<HistoryEntry> HistoryEntries
        {
            get
            {
                this.ReadSection();
                return this.historyEntries;
            }
        }

        /// <summary>
        /// Gets the last (most recent) history entry for the package.
        /// </summary>
        /// <remarks>
        /// This property assumes that the history list has been sorted after
        /// it was read from the SFT file.
        /// </remarks>
        public HistoryEntry LastHistoryEntry
        {
            get
            {
                this.ReadSection();
                return this.historyEntries[this.historyEntries.Count - 1];
            }
        }

        /// <summary>
        /// Reads the actual data for this section from the file.
        /// </summary>
        protected override void ReadSection()
        {
            if (this.SectionHasBeenRead)
            {
                return;
            }

            // Seek to the start of the data area for this section.
            long currentPosition = FileReader.BaseStream.Position;
            FileReader.BaseStream.Seek(this.StartPositionInFile + CommonSectionHeader.HeaderSize, System.IO.SeekOrigin.Begin);

            // Read the properties from the file.
            this.reserved = FileReader.ReadBytes(12);
            this.versionGuidCount = FileReader.ReadInt32();
            this.historyEntryCount = FileReader.ReadInt32();

            // Read the list of version GUIDs.
            this.versionGuids = new List<Guid>(this.versionGuidCount);
            for (int i = 0; i < this.versionGuidCount; i++)
            {
                byte[] guidBytes = FileReader.ReadBytes(16);
                this.versionGuids.Add(new Guid(guidBytes));
            }

            // Read the list of history entries.
            this.historyEntries = new List<HistoryEntry>(this.historyEntryCount);
            for (int i = 0; i < this.historyEntryCount; i++)
            {
                Version ver = HistoryEntry.GetHistoryEntryVersion(FileReader);
                if (ver.Major >= 4)
                {
                    if (ver.Minor >= 5)
                    {
                        HistoryEntry45 he = new HistoryEntry45(FileReader);
                        this.historyEntries.Add(he);
                    }
                    else
                    {
                        HistoryEntry4x he = new HistoryEntry4x(FileReader);
                        this.historyEntries.Add(he);
                    }
                }
                else
                {
                    // TODO: What if the major version number is less than 4?
                }
            }

            this.historyEntries.Sort();

            this.SectionHasBeenRead = true;
            FileReader.BaseStream.Seek(currentPosition, System.IO.SeekOrigin.Begin);
        }
    }
}
